﻿using MN.Framework.Common;
using MN.Framework.Common.Service;
using MN.Framework.UI.Win.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;

namespace MN.Framework.UI.Win.Controls
{
    public class MnSelector : RadDropDownList, IMnControl
    {

        #region Property
        ColumnInfo Clmn { get; set; }
        BaseContext Context { get; set; }
        BaseEntity Entity { get; set; }
        Type BaseEntityType { get; set; }
        public RadButton btn { get; set; }
        #endregion
        public MnSelector(Type baseEntityType, ColumnInfo clmn, BaseContext context, int controlWidth)
        {
            Entity = ServiceFactory.CreateRelatedEntity(baseEntityType, clmn.Name);
            BaseEntityType = baseEntityType;
            Clmn = clmn;
            Context = context;
            this.Width = controlWidth - 3;
            InitializeComponent();
        }

        void InitializeComponent()
        {           
            this.Name = Clmn.Name;
            this.PopupOpening += lookup_PopupOpening;
            this.ValueMember = "ID";
            this.DisplayMember = Entity.FirstOrDefaultDisplayField();
            var list = Context.RelationEntity(BaseEntityType, Clmn.Name);
            this.DataSource = list;
        }

        void lookup_PopupOpening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var lov = new MnLOVForm<BaseEntity, int>(Context, Entity);
            lov.FormClosing += lov_FormClosing;
            lov.ShowDialog();
            e.Cancel = true;
        }

        void lov_FormClosing(object sender, FormClosingEventArgs e)
        {
            var res = (sender as MnLOVForm<BaseEntity, int>).Result;
            if (res.ToString() != "0")
            {
                this.Text = res.ToString();
                this.SelectedValue = res;               
            }
        }



        public object getValue()
        {
            return this.SelectedValue;
        }

        public void setValue(object value)
        {
            this.SelectedValue = value;
        }
    }
}
